import PateoSearchForm from '@/components/common/PateoSearchForm';
import { filterAuth } from '@/support/common';
import { PlusOutlined } from '@ant-design/icons';
import { Button, Card, message, Table } from 'antd';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import PropTypes from 'prop-types';
import React, { PureComponent } from 'react';
import PateoAuthButtons from '../../../components/common/PateoAuthButtons/index';
import Ellipsis from '../../../components/Ellipsis';
import SIMDetailModal from '../../../components/simCard/simCardDetailModal';
import BindingEditModel from '../../../components/Tbox/tboxBindingModel';
import TboxDetailModal from '../../../components/Tbox/tboxDetailModel';
import VehicleDetailModal from '../../../components/vehicle/vinDetailModal';
import MaskText from '@/components/MaskText';

let page = '';
@connect((state: any) => ({
  tbox1: state.tbox1,
  loading: state.loading.effects['tbox1/getFetchPage'],
}))
export default class TboxList extends PureComponent {
  static contextTypes = {
    permissions: PropTypes.array,
  };
  state = {
    // bindingEditVisible: false,
    tboxDetailVisible: false,
    vinDetailVisible: false,
    simDetailVisible: false,
    tboxDetailModelData: {},
    vinDetailModelData: {},
    simDetailModelData: {},
    // bindingEditModelData: {},
    selectedRows: [],
    formValues: {},
  };

  handleFormReset = () => {
    const { dispatch } = this.props;
    this.state.formValues = {};
    dispatch({
      type: 'tbox1/getFetchPage',
      payload: {
        url: '/tbox/list',
      },
    });
  };

  handleSelectRows = (rows: any) => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleEditDate = (deviceId: any, sid: any) => {
    const { dispatch } = this.props;
    const obj = {};
    obj.pageObj = page;
    obj.values = this.state.formValues;
    dispatch({
      type: 'tbox1/getData',
      payload: {
        url: '/tbox/findbyid/' + sid,
      },
      callback: (data: any) => {
        let rdata = { ...data };
        rdata.sid = sid;
        dispatch(
          routerRedux.push({
            pathname: '/connectPlat/tbox/tboxEdit',
            flag: true,
            state: { data: rdata, obj },
          }),
        );
      },
    });
  };

  handleBindingDate = (record: any) => {
    const obj = record;
    obj.page = page;
    obj.formValues = this.state.formValues;
    this.bindRef.showModalEdit(obj);
  };

  handleRevokeCertification = (record: any) => {};

  // 验证deviceId是否存在
  checkUsername = (rule: any, value: any, callback: any) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'tbox1/checkDeviceId',
      payload: value,
      callback: (data: any) => {
        return data ? callback() : callback('tbox设备Id已存在');
      },
    });
  };

  handleDetailTbox = (deviceId: any) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'tbox1/getData',
      payload: {
        url: '/basedata/findtboxbydeviceid/' + deviceId,
      },
      callback: (response: any) => {
        if (response.statusCode === '0') {
          if (response.data) {
            this.setState({ tboxDetailModelData: response.data, tboxDetailVisible: true });
          }
        } else {
          message.error(response.statusMessage);
        }
      },
    });
  };

  handleDetailVIN = (vin: string) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'tbox1/getData',
      payload: {
        url: '/vehicle/findprofile/' + vin,
      },
      callback: (response: any) => {
        if (response.statusCode === '0') {
          if (response.data) {
            this.setState({ vinDetailModelData: response.data, vinDetailVisible: true });
          }
        } else {
          message.error(response.statusMessage).then(() => {});
        }
      },
    });
  };

  handleDetailSIM = (deviceId: string) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'tbox1/getData',
      payload: {
        url: '/simcard/findOneDeviceId/' + deviceId,
      },
      callback: (response: any) => {
        if (response.statusCode === '0') {
          if (response.data) {
            this.setState({ simDetailModelData: response.data, simDetailVisible: true });
          }
        } else {
          message.error(response.statusMessage).then(() => {});
        }
      },
    });
  };

  handleTableChange = (pagination: any, filters: any) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const { current, pageSize } = pagination;
    this.setState({ pagination });
    const params = {
      page: current - 1,
      size: pageSize,
      ...formValues,
      ...filters,
    };
    dispatch({
      type: 'tbox1/getFetchPage',
      payload: { url: '/tbox/list', ...params },
    });
  };

  componentDidMount() {
    const { dispatch } = this.props;
    // console.log('this.context.dicData', this.context.dicData);
    // const a = findDicByCode(this.context.dicData, 'deviceStatus');
    // console.log('aaaaaaaaaa', a);

    dispatch({
      type: 'tbox1/getFetchPage',
      payload: { url: '/tbox/list' },
    });
  }
  render() {
    const {
      tbox1: {
        pageData: { list, pagination },
      },
      loading,
      dispatch,
    } = this.props;

    page = pagination;
    const deviceStatus = ['出厂', '销售', '激活', '替换', '报废'];
    const columns = [
      {
        title: 'T-BOX编号',
        dataIndex: 'deviceId',
        width: 150,
        render: (text: any) => {
          return <a onClick={() => this.handleDetailTbox(text)}>{text}</a>;
        },
      },
      {
        title: 'IMEI',
        dataIndex: 'imei',
        width: 150,
      },
      {
        title: '软件版本',
        dataIndex: 'versionSoftware',
        width: 150,
        render: text => (
          <Ellipsis length={20} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '硬件版本',
        dataIndex: 'versionHardware',
        width: 150,
        render: text => (
          <Ellipsis length={20} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '蓝牙识别码',
        dataIndex: 'deviceSkey',
        width: 150,
      },
      {
        title: '状态',
        dataIndex: 'deviceStatus',
        width: 50,
        render: (text: any) => {
          return deviceStatus[text];
        },
      },
      {
        title: '入库时间',
        dataIndex: 'createDate',
        width: 150,
      },
      {
        title: 'VIN号',
        dataIndex: 'vin',
        width: 150,
        render: (text: any) => {
          return <a onClick={() => this.handleDetailVIN(text)}>{text}</a>;
        },
      },
      {
        title: 'SIM卡号',
        dataIndex: 'sim',
        width: 150,
        render: (text: any) => {
          return (
            <a onClick={() => this.handleDetailSIM(text)}>
              <MaskText text={text} type="simCard" />
            </a>
          );
        },
      },
      {
        title: '操作',
        dataIndex: '操作',
        width: 120,
        fixed: 'right',
        render: (text: any, record: any) => {
          const editBtn = {
            title: '编辑',
            key: 'edit',
            auth: 'tbox-opt',
            onConfirm: () => this.handleEditDate.bind(this)(record.deviceId, record.sid),
          };
          const bindBtn = {
            title: '修改绑定关系',
            key: 'editBinding',
            auth: 'tbox-opt',
            onConfirm: () => this.handleBindingDate.bind(this)(record),
          };
          const revokeBtn = {
            title: '撤销证书',
            key: 'revokeCertification',
            auth: 'tbox-opt',
            onConfirm: () => this.handleRevokeCertification.bind(this)(record),
          };
          const btns = [];
          btns.push(editBtn);
          if (!(record && record.projectId && record.projectId === 'dfspt')) {
            btns.push(bindBtn);
          }
          // btns.push(revokeBtn);
          return <PateoAuthButtons btns={btns} pathname={this.props.location.pathname} />;
        },
      },
    ];

    const paginationProps = {
      pageSizeOptions: [10, 20, 50],
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };

    const searchItems = [
      {
        type: 'input',
        title: 'T-BOX编号',
        key: 'deviceId',
      },
      {
        type: 'input',
        title: 'IMEI',
        key: 'imei',
      },
      {
        type: 'input',
        title: '软件版本',
        key: 'versionSoftware',
      },
      {
        type: 'input',
        title: '硬件版本',
        key: 'versionHardware',
      },
    ];
    return (
      <div>
        <Card bordered={false}>
          {/* search form */}
          <PateoSearchForm
            onRef={(val: any) => (this.searchForm = val)}
            searchItems={searchItems}
            fetchParams={{ type: 'tbox1/getFetchPage', url: '/tbox/list', extraArgs: {} }}
            saveFormValues={(val: any) => {
              this.setState({
                formValues: Object.assign(this.state.formValues, val),
              });
            }}
            handleFormReset={this.handleFormReset}
          />
        </Card>

        <Card style={{ marginTop: 12 }} bordered={false}>
          {/* add */}
          <div>
            {filterAuth('tbox-opt', this.context.permissions, this.props.location.pathname) ? (
              <div className="my_newItem">
                <Button
                  icon={<PlusOutlined />}
                  type="primary"
                  size="small"
                  onClick={() => this.props.history.push('/connectPlat/tbox/tboxAdd')}
                >
                  新增
                </Button>
              </div>
            ) : null}
          </div>

          {/* table */}
          <Table
            size={'small'}
            rowKey={record => record.sid}
            dataSource={list}
            loading={loading}
            columns={columns}
            pagination={paginationProps}
            onChange={this.handleTableChange}
            scroll={{ x: '170%' }}
          />
        </Card>

        {/* tbox详情 */}
        <TboxDetailModal
          changeVisible={() => this.setState({ tboxDetailVisible: false, tboxDetailModelData: {} })}
          visible={this.state.tboxDetailVisible}
          detailModelData={this.state.tboxDetailModelData}
          dispatch={dispatch}
        />

        {/* sim卡详情 */}
        <SIMDetailModal
          changeVisible={() => this.setState({ simDetailVisible: false, simDetailModelData: {} })}
          visible={this.state.simDetailVisible}
          detailModelData={this.state.simDetailModelData}
          dispatch={dispatch}
        />

        {/* vin号详情查看 */}
        <VehicleDetailModal
          changeVisible={() => this.setState({ vinDetailVisible: false, vinDetailModelData: {} })}
          visible={this.state.vinDetailVisible}
          detailModelData={this.state.vinDetailModelData}
          dispatch={dispatch}
        />

        {/* 修改绑定关系 */}
        <BindingEditModel
          onRef={(val: any) => (this.bindRef = val)}
          icon="plus"
          type="primary"
          title="修改绑定关系"
          dispatch={this.props.dispatch}
          resetOutterForm={this.handleFormReset}
        />
      </div>
    );
  }
}
